<template>
  <div class="app-container">
    <el-row>
      <el-form
        label-position="right"
        label-width="80px"
        :rules="rules"
        :model="house"
        ref="houseForm"
      >
        <el-col :span="12">
          <el-form-item
            label="审核"
            prop="isReviewed"
          >
            <el-radio-group
              v-model="house.isReviewed"
              size="medium"
            >
              <el-radio-button :label="0">待审核</el-radio-button>
              <el-radio-button :label="1">通过</el-radio-button>
              <el-radio-button :label="2">未通过</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="标题"
            prop="title"
          >
            <el-input
              v-model="house.title"
              clearable
              style="width:350px"
            />
          </el-form-item>

          <el-form-item
            label="描述"
            prop="advantage"
          >
            <el-input
              v-model="house.advantage"
              clearable
              style="width:350px"
            />
          </el-form-item>

          <el-form-item
            label="地址"
            prop="address"
          >
            <el-input
              v-model="house.address"
              clearable
              style="width:350px"
            />
          </el-form-item>

          <el-form-item
            label="房租"
            prop="price"
          >
            <el-input
              v-model="house.price"
              clearable
              style="width:100px"
            />
            <span>￥/月</span>
          </el-form-item>

          <el-form-item
            label="面积"
            prop="area"
          >
            <el-input
              v-model="house.area"
              clearable
              style="width:100px"
            />
            <span>㎡</span>
          </el-form-item>

          <el-form-item
            label="类型"
            prop="typeId"
          >
            <el-radio-group
              v-model="house.typeId"
              size="medium"
            >
              <el-radio-button :label="0">新房</el-radio-button>
              <el-radio-button :label="1">二手房</el-radio-button>
              <el-radio-button :label="2">商业租房</el-radio-button>
              <el-radio-button :label="100">其他</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="发布时间"
            prop="houseDate"
          >        
            <el-date-picker
               v-model="house.houseDate"
               type="date"
               placeholder="选择日期"
              value-format="yyyy-MM-dd"
               :picker-options="pickerOptions"
            />
          </el-form-item>

          <el-form-item label="用户ID">
            <el-input
              v-if="isCreate == false"
              v-model="house.userId"
              disabled
              style="width:100px"
            />
            <el-input
              v-if="isCreate == true"
              v-model="userId"
              disabled
              style="width:100px"
            />
          </el-form-item>

          <el-form-item label="用户名">
            <el-input
              v-if="isCreate == false"
              v-model="house.userName"
              disabled
              style="width:100px"
            >
            </el-input>
            <el-input
              class="userId"
              v-if="isCreate == true"
              v-model="name"
              disabled
              style="width:100px"
            >
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              :disable="saveBtnDisabled"
              type="primary"
              @click="saveOrUpdate('houseForm')"
            >保存</el-button>
            <el-button @click="resetForm('houseForm')">重置</el-button>
          </el-form-item>

        </el-col>

        <el-col :span="12">
          <el-form-item label="图片">
            <el-image
              style="width: 500px; height: 300px"
              :src="house.img"
              fit="contain"
            ></el-image>
          </el-form-item>

          <el-form-item label="更换图片">
            <!-- 文件上传按钮 -->
            <el-button
              type="primary"
              icon="el-icon-upload"
              @click="imageCropperShow=true"
            >上传图片</el-button>
            <!-- 
              v-show：是否显示上传组件
              :ki：类似于id，如果一个页面多个图片上传控件，可以
              :url：后台上传的url地址
              @close：关闭上传组件
              @crop-upload-success：上传成功后的回调
            -->
            <image-cropper
              v-show="imageCropperShow"
              :ki="imageCropperKey"
              :url="'/oss/house'"
              field="file"
              width="500"
              height="300"
              noCircle="true"
              noSquare="true"
              @close="close"
              @crop-upload-success="cropSuccess"
            />
          </el-form-item>
        </el-col>
      </el-form>

    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import house from '@/api/house';
import user from '@/api/user';
import { getElement } from 'dropzone';
import ImageCropper from '@/components/ImageCropper';

const defaultForm = {
  title: '',
  advantage: '',
  address: '',
  price: '',
  area: '',
  typeId: 100,
  houseDate: '',
  isReviewed: '',
  img: ''
};

export default {
  components: { ImageCropper },
  data() {
    return {
      house: {
        title: '',
        advantage: '',
        address: '',
        price: '',
        area: '',
        typeId: 100,
        houseDate: '',
        isReviewed: '',
        userId: '',
        userName: '',
        img: ''
      },
      isCreate: false,
      saveBtnDisabled: false, // 保存按钮是否禁用
      imageCropperShow: false, // 上传头像组件是否显示
      imageCropperKey: 0, // 上传组件key值
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          },
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          },
          {
            text: '明天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['name', 'userId'])
  },
  // 监听
  watch: {
    // 当路由发生变化, 方法执行
    $route(to, from) {
      this.init();
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      // params表示路由中的参数, 指 path: 'edit/:id' 中类似:id的参数
      // 注意是route不是router
      if (this.$route.params && this.$route.params.id) {
        this.isCreate = false;
        const id = this.$route.params.id;
        this.fetchDataById(id);
      } else {
        // 否则新增一条记录后, defaultForm就变成了之前新增的值
        // 使用对象拓展运算符, 拷贝对象, 而不是引用
        this.isCreate = true;
        this.house = { ...defaultForm };
        this.house.userId = this.$store.state.user.userId;
        this.house.userName = this.$store.state.user.name;
      }
    },
    // 通过id获取项目
    fetchDataById(id) {
      house
        .getHouseById(id)
        .then(response => {
          this.house = response.data.house;
        })
        .catch(response => {
          this.$message({
            type: 'error',
            message: '获取数据失败'
          });
        });
    },
    // 新建或修改
    saveOrUpdate(formName) {
      this.saveBtnDisabled = true;
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 如果house对象中有houseId, 说明是修改, 因为创建不需要输入houseId
          // 这个house对象是后端返回给前端的, 不是data中的
          if (this.house.houseId) {
            this.updateData();
          } else {
            this.saveData();
          }
        } else {
          console.log('error submit');
          return false;
        }
      });
    },
    // 保存房源
    saveData() {
      house
        .saveHouse(this.house)
        .then(response => {
          return this.$message({
            type: 'success',
            message: '保存成功'
          });
        })
        .then(response => {
          // 保存成功跳转到表格页面
          this.$router.push({ path: '/house' });
        })
        .catch(response => {
          this.$message({
            type: 'error',
            message: '保存失败'
          });
        });
    },
    // 修改房源
    updateData() {
      this.saveBtnDisabled = true;
      house
        .updateHouse(this.house)
        .then(response => {
          this.$message({
            type: 'success',
            message: '修改成功'
          });
        })
        .then(response => {
          this.$router.push({ path: '/house' });
        })
        .catch(response => {
          this.$message({
            type: 'error',
            message: '保存失败'
          });
        });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 关闭上传弹窗
    close() {
      this.imageCropperShow = false;
      //上传组件初始化
      this.imageCropperKey = this.imageCropperKey + 1;
    },
    // 上传成功方法
    cropSuccess(data) {
      // 上传之后接口返回图片地址
      this.house.img = data.url;
      console.log(this.house.img);
      this.close();
    }
  }
};
</script>
<style scoped>
span {
  color: #606266;
  margin-left: 12px;
  font-size: 14px;
  font-weight: 700;
}
</style>